package net.sureon.web.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.biz.CompanyBO;
import net.sureon.biz.CompanyMgr;
import net.sureon.common.exception.SureonException;
import net.sureon.dao.BalanceOperation;
import net.sureon.dao.ConsumeRecord;
import net.sureon.web.Login;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class CostChange implements Controller{
	private static final Log logger = LogFactory.getLog(CostChange.class);
	private CompanyMgr companyMgr;
	private static final String BALANCE_OPERATION_DISPLAY_RESULT = "BalanceOperationDisplayResult";
	private static final String SITEURL_DORPDOWN_DISPLAY_LIST = "siteURLDropDownDisplayList";
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		/*
		 * 处理充值流程
		 */
		String operationType = request.getParameter("operationType");
		if("Save".equals(operationType)) {
//			String companyFullName = request.getParameter("companyFullName");
			String siteURL = request.getParameter("siteURL");
			long companyID = 0;
			net.sureon.biz.CompanyBO company = null;
			company = companyMgr.getCompany(siteURL);
			if(company != null) {
				
				String amount = request.getParameter("amount");
				String comments = request.getParameter("comments");
				
				companyID = company.getCompanyID();
				BalanceOperation operation = new BalanceOperation();
				operation.setOperationDate(new java.util.Date());
				operation.setOperationType(BalanceOperation.OPR_TYPE_SAVE);
				operation.setComments(comments);
				
				float theAmount = 0;
				try {
					theAmount = Float.parseFloat(amount);
				} catch(Exception e) {
					logger.error(e);
					throw new SureonException("parameter_not_allow");
				}
				float theBalance = companyMgr.getCompanyBalance(companyID) + theAmount;
				
				operation.setAmount(theAmount);

				operation.setBalance(theBalance);
				operation.setCompanyID(companyID);
				
				companyMgr.insertBalanceOperation(operation);
				
			}
		} 
		
		/*
		 * 处理显示客户充值信息流程
		 */
		List<BalanceOperation> list = null;
		String filter = request.getParameter("filter");
		SimpleDateFormat formatToDate =new SimpleDateFormat("yyyy-MM-dd");
		if("true".equals(filter)) {
			long companyID = -1;
			try {
				companyID = Long.parseLong(request.getParameter("companyID"));
			} catch(Exception e) {
				logger.warn("the companyID parse error, companyID = " + request.getParameter("companyID"));
			}
			String strStartDate = request.getParameter("startDate");
			String strEndDate = request.getParameter("endDate");
			Date startDate = null;
			Date endDate = null;
			if(!(companyID > 0)) {
				if(!"".equals(strStartDate) && !"".equals(strEndDate)) {
					try {
						startDate = formatToDate.parse(strStartDate);
						endDate = formatToDate.parse(strEndDate);
					} catch(Exception e) {
						logger.error(e);
						throw new SureonException("date_format_not_allow");
					}
					list = addSiteURLToBalanceOperation(getBalanceOperationInRangeDate(startDate, endDate));
				} else if(!"".equals(strStartDate) && "".equals(strEndDate)){
					try {
						startDate = formatToDate.parse(strStartDate);
						endDate = new java.util.Date();
					}catch(Exception e) {
						logger.error(e);
						throw new SureonException("date_format_not_allow");
					}
					list = addSiteURLToBalanceOperation(getBalanceOperationInRangeDate(startDate, endDate));
				} else if("".equals(strStartDate) && "".equals(strEndDate)) {
					list = addSiteURLToBalanceOperation(allBalanceOperation());
				} else if(!"".equals(strEndDate) && "".equals(strStartDate)){
					try {
						endDate = formatToDate.parse(strEndDate);
						startDate = new java.util.Date();
					} catch(Exception e) {
						logger.error(e);
						throw new SureonException("date_format_not_allow");
					}
					list = addSiteURLToBalanceOperation(getBalanceOperationInRangeDate(startDate, endDate));
				} else {
					list = new ArrayList<BalanceOperation>();
				}
				
			} else {
				// 选择了公司
				if(!"".equals(strStartDate) && !"".equals(strEndDate)) {
					try {
						startDate = formatToDate.parse(strStartDate);
						endDate = formatToDate.parse(strEndDate);
					} catch(Exception e) {
						logger.error(e);
						throw new SureonException("date_format_not_allow");
					}
					list = addSiteURLToBalanceOperation(getBalanceOperationInRangeDateByCompanyId(companyID, startDate, endDate));
				} else if(!"".equals(strStartDate) && "".equals(strEndDate)){
					try {
						startDate = formatToDate.parse(strStartDate);
						endDate = new java.util.Date();
					} catch(Exception e) {
						logger.error(e);
						throw new SureonException("date_format_not_allow");
					}
					list = addSiteURLToBalanceOperation(getBalanceOperationInRangeDateByCompanyId(companyID, startDate, endDate));
				} else if("".equals(strStartDate) && "".equals(strEndDate)) {
					list = addSiteURLToBalanceOperation(getBalanceOperationByCompanyID(companyID));
				} else if(!"".equals(strEndDate) && "".equals(strStartDate)){
					try {
						endDate = formatToDate.parse(strEndDate);
						startDate = new java.util.Date();
					} catch(Exception e) {
						logger.error(e);
						throw new SureonException("date_format_not_allow");
					}
					list = addSiteURLToBalanceOperation(getBalanceOperationInRangeDateByCompanyId(companyID, startDate, endDate));
				} else {
					list = new ArrayList<BalanceOperation>();
				}
				request.setAttribute("companyID", companyID);
			}
			request.setAttribute("startDate", strStartDate);
			request.setAttribute("endDate", strEndDate);
		} else {
			list = addSiteURLToBalanceOperation(allBalanceOperation());
		}
		request.setAttribute(SITEURL_DORPDOWN_DISPLAY_LIST, buildSiteURLResult());
		request.setAttribute(BALANCE_OPERATION_DISPLAY_RESULT, list);
		
		return new ModelAndView("sysAdmin/costChange");
	}
	
	private List<BalanceOperation> allBalanceOperation() {
		return companyMgr.getAllCompanyBalanceOperation();
	}
	
	private List<BalanceOperation> getBalanceOperationInRangeDate(Date startDate, Date endDate) {
		java.util.Calendar cal = java.util.Calendar.getInstance();
		cal.setTime(endDate);
		cal.roll(java.util.Calendar.DATE, 1);
		return companyMgr.getBalanceOperationByOperationDate(startDate, cal.getTime());
	}
	
	private List<BalanceOperation> getBalanceOperationInRangeDateByCompanyId(long companyID, Date startDate, Date endDate) {
		java.util.Calendar cal = java.util.Calendar.getInstance();
		cal.setTime(endDate);
		cal.roll(java.util.Calendar.DATE, 1);
		return companyMgr.getBalanceOperationByCompanyIDAndOperationDate(companyID, startDate, cal.getTime());
	}
	private List<BalanceOperation> getBalanceOperationByCompanyID(long companyID) {
		return companyMgr.getRecentTenBalanceOperation(companyID);
	}
	
	private List<CompanyBO> buildSiteURLResult() throws SureonException {
		return companyMgr.getAllCompanies();
	}
	
	private List<BalanceOperation> addSiteURLToBalanceOperation(List<BalanceOperation> list) throws SureonException {
		CompanyBO company = null;
		for(BalanceOperation operation : list) {
			long companyID = operation.getCompanyID();
			company = companyMgr.getCompany(companyID);
			operation.setCompanyFullName(company.getCompanyVO().getCompanyFullName());
			operation.setSiteURL(company.getCompanyVO().getSiteURL());
		}
		return list;
	}
	
	
	public CompanyMgr getCompanyMgr() {
		return companyMgr;
	}
	public void setCompanyMgr(CompanyMgr companyMgr) {
		this.companyMgr = companyMgr;
	}
}
